package com.da.sumup.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.da.sumup.dao.bean.ArticleDO;
import com.da.sumup.dao.bean.CatalogueDO;
import com.da.sumup.dao.repsository.CatalogueRepository;
import com.da.sumup.pojo.TreeData;
import com.da.sumup.service.IArticleService;
import com.da.sumup.service.ICatalogueService;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CatalogueServiceImpl implements ICatalogueService {


    private final IArticleService articleService;
    private final CatalogueRepository catalogueRepository;

    public CatalogueServiceImpl(CatalogueRepository catalogueRepository, IArticleService articleService) {
        this.catalogueRepository = catalogueRepository;
        this.articleService = articleService;
    }

    @Override
    public List<CatalogueDO> findAll() {
        return catalogueRepository.findAll(Sort.by(Sort.Direction.ASC, "sort"));
    }

    @Override
    public JSONArray findDict() {
        JSONArray treeData = new JSONArray();
        List<CatalogueDO> catalugues = findAll();
        List<ArticleDO> articleDOS = articleService.findAll();
        for(CatalogueDO cata:catalugues){
            JSONObject parent = new JSONObject();
            treeData.add(parent);
            parent.put("id",cata.getUuid());
            parent.put("title",cata.getCatalogueName());
            JSONArray parentTree = new JSONArray();
            parent.put("children",parentTree);
            for(ArticleDO article:articleDOS){
                if(cata.getUuid().equals(article.getCatalogueUuid())){
                    JSONObject children = new JSONObject();
                    children.put("id",article.getUuid());
                    children.put("title",article.getTitle());
                    parentTree.add(children);
                }
            }
        }
        return treeData;
    }
}
